package com.ai.ubssapp.interceptor;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.ai.ubssapp.annotation.ParamCheck;
import com.ai.ubssapp.bean.RespInfo;
import com.ai.ubssapp.enums.SysCode;
import com.alibaba.fastjson.JSONArray;

/**
 * 参数校验器拦截
 *
 */
public class ParamCheckInterceptor /*extends BaseInterceptor*/ extends HandlerInterceptorAdapter{
	
	/**
	 * 参数校验器拦截
	 * 
	 */
	@SuppressWarnings("deprecation")
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		if(handler instanceof HandlerMethod){
			HandlerMethod method = (HandlerMethod)handler;
	    	//获取方法指定的校验参数注解
			ParamCheck paramCheck = method.getMethodAnnotation(ParamCheck.class);
	    	
			//1、校验时间ticket开关，开关打开后，不管ParamCheck指定都需要校验
//			String timeTicket = SpringPropertyHolder.getContextProperty("validate.timeTicket", "true");
//			if("true".equals(timeTicket)){
//				//校验ticket
//				String grantTicket = request.getParameter(Configs.PARAM_GRANT_TICKET);
//				String[] ret = TimeTicketUtil.checkTimeTiket(grantTicket);
//				if(!"0".equals(ret[0])){
//					writerRespInfo(response, ret[0], ret[1]);
//					return false;
//				}
//			}
	    	
	    	//2、指定需要校验的参数
	    	if(!StringUtils.isEmpty(paramCheck) && paramCheck.value().length > 0 && !"".equals(paramCheck.value()[0])){
	    		String[] paras = paramCheck.value();
	    		for (String para : paras) {
	    			String paraValue = request.getParameter(para.trim());
	    			
	    			//不能为空
					if(StringUtils.isEmpty(paraValue)){
						writerRespInfo(response, "-1", para.trim() + "不能为空！");
			    		return false;
					}
					
					//如果是系统类型，校验是否在系统类型枚举中
					if("sysCode".equals(para.trim())){
						boolean flag = false;
						for (SysCode sysCode : SysCode.values()) {
							if(sysCode.toString().equals(paraValue)){
								flag = true;
							}
						}
						if(!flag){
							writerRespInfo(response, "-1", "sysCode参数不合法！");
				    		return false;
						}
					}
				}
	    	}
	    }
	    return true;
	}
	
	/**
	 * 向浏览器写返回信息
	 * 
	 * @param respCode
	 * @param respDesc
	 * @return
	 * @throws IOException 
	 */
	@SuppressWarnings("unchecked")
	private void writerRespInfo(HttpServletResponse response, String respCode, String respDesc) throws IOException{
		RespInfo respInfo = new RespInfo();
		respInfo.setRespCode(respCode);
		respInfo.setRespDesc(respDesc);
		
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=utf-8");
		response.getWriter().write(JSONArray.toJSONString(respInfo));
	}	
}
